/*
 * @(#)FileOperation.java    �汾�� 2010-11-3
 * 
 * Version information
 * 
 * Copyright notice
 */

package cn.edu.nju.software.localserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Class description goes here.
 * 
 * @version �汾�� 2010-11-3
 * @author lijinsheng
 */
public class FileHandler {
	/* This class is read or write the file with the stream */

	private FileHandler() {

	}

	public static void readFile(File xmlFile, DataInputStream inputStream) {
		System.out.println("Enter ReadFile");
		DataOutputStream fileOut = null;
		try {
			int bufferSize = 8192;
			byte[] buf = new byte[bufferSize];
			fileOut = new DataOutputStream(new BufferedOutputStream(
					new BufferedOutputStream(new FileOutputStream(xmlFile))));
			while (true) {
				int read = 0;
				if (inputStream != null) {
					System.out.println("before read");
					read = inputStream.read(buf);
					System.out.println("after read");
					System.out.println(read);
				}
				if (read == -1) {
					break;
				}
				System.out.println("before write");
				fileOut.write(buf, 0, read);
				System.out.println("after write");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			fileOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Finish read File");
	}

	public static void writeFile(File xmlFile, DataOutputStream outputStream) {
		DataInputStream fis = null;
		try {
			fis = new DataInputStream(new BufferedInputStream(
					new FileInputStream(xmlFile)));

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		byte[] buf = new byte[(int) xmlFile.length()];

		while (true) {
			int read = 0;
			if (fis != null) {
				try {
					read = fis.read(buf);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (read == -1) {
				break;
			}
			try {
				outputStream.write(buf, 0, read);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			outputStream.flush();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}
}
